package com.siteseat.common.json.prettyprint;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import com.siteseat.common.misc.IOHelper;
import com.sun.jersey.spi.container.ContainerResponse;
import com.sun.jersey.spi.container.ContainerResponseWriter;

public class PrettyResponseAdapter implements ContainerResponseWriter {

  private final ContainerResponseWriter crw;

  private ByteArrayOutputStream         buffer;

  private ContainerResponse             response;

  public PrettyResponseAdapter( ContainerResponseWriter crw ) {
    this.crw = crw;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public OutputStream writeStatusAndHeaders( long contentLength, ContainerResponse cResponse ) throws IOException {
    this.response = cResponse;
    this.buffer = new ByteArrayOutputStream();

    return this.buffer;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public void finish() throws IOException {
    byte[] content = this.buffer.toByteArray();
    OutputStream out = this.crw.writeStatusAndHeaders( -1L, this.response );
    String contentText = new String( content, IOHelper.CHARSET );
    contentText = PrettyPrintIndenter.indentJSON( contentText );
    out.write( contentText.getBytes( IOHelper.CHARSET ) );
  }
}